package kcp

import (
	"net"

	"github.com/xtaci/kcp-go/v5"

	"gitee.com/hasika/common-server/conn/impl_base"
	"gitee.com/hasika/common-server/conn/inet"
	"gitee.com/hasika/common-server/option"
)

type Connection struct {
	UDPSession *kcp.UDPSession
	*impl_base.Connection
}

func (t *Connection) GetRemote() net.Addr {
	return t.UDPSession.RemoteAddr()
}

func (t *Connection) CloseConn() error {
	return t.UDPSession.Close()
}

func NewKcpConnection(kcpConnection *kcp.UDPSession, option *option.KcpOption) *Connection {
	if option != nil {
		kcpConnection.SetStreamMode(option.StreamMode)
		kcpConnection.SetWriteDelay(option.WriteDelay)
		kcpConnection.SetNoDelay(option.NoDelayMode, int(option.Interval.Milliseconds()), option.ResendMode, option.NoCrowdControl)
		kcpConnection.SetWindowSize(option.SendWindowSize, option.RcvWindowSize)
		kcpConnection.SetACKNoDelay(option.AckNoDelay)
		kcpConnection.SetMtu(option.Mtu)
	}
	return &Connection{UDPSession: kcpConnection, Connection: impl_base.NewBaseConnection()}
}

func (t *Connection) GetConnectionType() inet.ConnectionType {
	return inet.Kcp
}

func (t *Connection) InitFd() {

}

func (t *Connection) LowerWrite(data []byte) error {
	return t.WriteWithLimit(t.UDPSession, data)
}

func (t *Connection) Read(p []byte) (n int, err error) {
	defer func() {
		t.RecordRead(n)
	}()
	return t.UDPSession.Read(p)
}
